'use strict';

const crypto = require('crypto');
const BaseController = require('../../core/base_controller');
const Op = require('sequelize').Op;

class UserController extends BaseController {
  // 登录
  async login() {
    const { ctx } = this;
    const rules = {
      phone: {
        type: 'string',
        required: true,
        format: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号',
      },
      password: {
        type: 'string',
        required: true,
        min: 6,
        max: 20,
        message: '密码长度应在6-20个字符之间',
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      const errors = err.errors.map(error => rules[error.field].message).map(el=>el.string).join();
      ctx.throw(400, errors);
    }

    const { phone, password } = ctx.request.body;

    // 查找用户
    const user = await ctx.model.User.findOne({
      where: {
        phone,
        status:1,
        user_type: {
          [Op.in]: ['admin', 'employer','chef']
        },
      },
    });

    if (!user) {
      ctx.throw(400, '用户不存在或已被禁用');
    }

    // 验证密码
    const hashedPassword = crypto.createHash('md5')
      .update(password)
      .digest('hex');

    if (hashedPassword !== user.password) {
      ctx.throw(400, '密码错误');
    }

    if (user.status === 0) {
      ctx.throw(403, '该账号已被禁用');
    }

    // 生成 token
    const token = this.app.jwt.sign({
      user_id: user.user_id,
      phone: user.phone,
      user_type: user.user_type,
    }, this.app.config.jwt.secret, {
      expiresIn: '7d',
    });
    delete user.dataValues.password
    // 更新登录时间
    await user.update({
      updated_at: new Date(),
    });

    // 返回前端需要的格式
    this.success({
      token,
      userInfo: user
    });
  }

  // 获取当前用户信息
  async getUserInfo() {
    const { ctx } = this;
    console.log(ctx.headers,666)
    const { user_id } = ctx.headers

    const user = await ctx.model.User.findByPk(user_id);
    if (!user) {
      ctx.throw(404, '用户不存在');
    }

    // 返回前端需要的格式
    this.success(user);
  }

  // 退出登录
  async logout() {
    // 这里可以添加token黑名单等逻辑
    this.success(null, '退出成功');
  }

  // 获取用户列表
  async index() {
    const { ctx } = this;
    const result = await ctx.service.user.findAll(ctx.query);
    this.success(result);
  }

  // 获取单个用户
  async show() {
    const { ctx } = this;
    const user = await ctx.service.user.findById(ctx.params.id);
    this.success(user);
  }

  // 创建用户
  async create() {
    const { ctx } = this;
    const rules = {
      phone: {
        type: 'string',
        required: true,
        format: /^1[3-9]\d{9}$/,
        message: '手机号格式不正确',
      },
      password: {
        type: 'string',
        required: true,
        min: 6,
        max: 20,
        message: '密码长度应在6-20个字符之间',
      },
      user_type: {
        type: 'enum',
        values: ['user','employer','admin'],
        required: true,
        message: '用户类型枚举值错误',
      },
      gender: {
        type: 'enum',
        values: ['man','woman','secret'],
        required: false,
        message: '性别枚举值错误',
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
       const errors = err.errors.map(error => rules[error.field].message).map(el=>el.string).join();
      console.log(errors)
       ctx.throw(400, errors);
    }

    // 检查手机号是否已存在
    const existingUser = await ctx.model.User.findOne({
      where: { phone: ctx.request.body.phone }
    });

    if (existingUser) {
      ctx.throw(400, '该手机号已被注册');
    }

    const user = await ctx.service.user.create(ctx.request.body);
    this.success(user);
  }

  // 更新用户
  async update() {
    const { ctx } = this;
    const rules = {
      phone: {
        type: 'string',
        required: true,
        format: /^1[3-9]\d{9}$/,
        message: '手机号格式不正确',
      },
      password: {
        type: 'string',
        required: true,
        min: 6,
        max: 20,
        message: '密码长度应在6-20个字符之间',
      },
      user_type: {
        type: 'enum',
        values: ['user','employer','admin'],
        required: true,
        message: '用户类型枚举值错误',
      },
      gender: {
        type: 'enum',
        values: ['man','woman','secret'],
        required: false,
        message: '性别枚举值错误',
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
       const errors = err.errors.map(error => rules[error.field].message).map(el=>el.string).join();
      ctx.throw(400, errors);
    }

    // 检查手机号是否已被其他用户使用
    const existingUser = await ctx.model.User.findOne({
      where: {
        phone: ctx.request.body.phone,
        user_id: { [Op.ne]: ctx.params.id } // 排除当前用户
      }
    });

    if (existingUser) {
      ctx.throw(400, '该手机号已被其他用户使用');
    }

    const user = await ctx.service.user.update(ctx.params.id , ctx.request.body);
    this.success(user);
  }

  // 删除用户
  async destroy() {
    const { ctx } = this;
    await ctx.service.user.destroy(ctx.params.id);
    this.success(null, '删除成功');
  }

  // 更新用户状态
  async updateStatus() {
    const { ctx } = this;
    const rules = {
      status: {
        type: 'enum',
        values: [0, 1,true,false],
        required: true,
        message: '状态值错误，应为：0-禁用，1-正常',
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
       const errors = err.errors.map(error => rules[error.field].message).map(el=>el.string).join();
      console.log(err)
      ctx.throw(400, errors);
    }

    await ctx.service.user.updateStatus(ctx.params.id, ctx.request.body.status);
    this.success(null, '状态更新成功');
  }
}

module.exports = UserController;
